from PIL import Image
import os



# 旋转指定尺寸的图片
def rotate_images_in_folder(folder_path):
    # 遍历指定文件夹下的所有文件
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)

        # 确保是文件且为图片文件
        if os.path.isfile(file_path) and (file_path.lower().endswith('.jpg') or file_path.lower().endswith('.png')):
            try:
                # 打开图片
                with Image.open(file_path) as img:
                    # 检查图片尺寸是否为3000*4000
                    if img.size == (3000, 4000):
                        # 顺时针旋转90度
                        rotated_img = img.transpose(Image.ROTATE_90)

                        # 保存旋转后的图片，覆盖原图
                        rotated_img.save(file_path)
                        print(f"Rotated: {file_path}")
                    else:
                        print(f"Skipped: {file_path} - 不是3000*4000分辨率")
            except IOError as e:
                print(f"Error processing {file_path}: {e}")

# 更改图片尺寸
def resize_images_in_folder(folder_path):
    # 遍历指定文件夹下的所有文件
    for filename in os.listdir(folder_path):
        file_path = os.path.join(folder_path, filename)

        # 确保是文件且为图片文件
        if os.path.isfile(file_path) and (file_path.lower().endswith('.jpg') or file_path.lower().endswith('.png')):
            try:
                # 打开图片
                with Image.open(file_path) as img:
                    # 检查图片尺寸是否为4000*3000
                    if img.size == (4000, 3000):
                        # 计算新的宽度和高度，保持原图的宽高比
                        new_width = 800
                        new_height = int((new_width / img.width) * img.height)

                        # 等比例缩放图片，使用LANCZOS过滤器进行高质量缩放
                        resized_img = img.resize((new_width, new_height), resample=Image.LANCZOS)

                        # 保存缩放后的图片，覆盖原图
                        resized_img.save(file_path)
                        print(f"Resized: {file_path}")
                    else:
                        print(f"Skipped: {file_path} - 不是4000*3000分辨率")
            except IOError as e:
                print(f"Error processing {file_path}: {e}")


if __name__ == '__main__':
    # 使用示例：将下面的'your_folder_path'替换为你的文件夹路径
    folder_path = r"C:\Users\64531\Desktop\杂草类别1\img"
    # rotate_images_in_folder(folder_path)
    resize_images_in_folder(folder_path)